package com.qingfeng.client.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qingfeng.base.exception.LsException;
import com.qingfeng.base.model.Page;
import com.qingfeng.base.util.CodeEnum;
import com.qingfeng.client.bean.*;
import com.qingfeng.client.dao.*;
import com.qingfeng.client.util.TradeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author ff
 * @Data 2017/11/6 16:20
 */
@Service
public class TradeService {

    @Resource
    private TradeMapper tradeDao;

    @Resource
    private OrderGoodsMapper orderGoodsDao;

    @Resource
    private LogisticsMapper logisticsDao;

    @Resource
    private LogisticsCompanyMapper logisticsCompanyMapper;

    @Resource
    private OrderStoreMapper orderStoreDao;

    @Resource
    private BuyerMapper buyerMapper;

    @Resource
    private StoreMapper storeMapper;

    @Autowired
    private DealQueueService dealQueueService;


    public List getPageList(Page page, Trade bean, Long storeId) {
        return tradeDao.getPageList(page, bean, storeId);
    }

    /**
     * 查询一笔交易的详细情况
     *
     * @param id
     * @return
     */
    public JSONObject getDetail(Long id) {
        Long t = System.currentTimeMillis();
        OrderStore orderStore = orderStoreDao.selectById(id);
        Logistics logistics = logisticsDao.selectById(orderStore.getLogisticsId());
        List<OrderGoods> list = orderGoodsDao.getByTradeIdAndStoreId(orderStore.getTradeId(),orderStore.getStoreId());
        Buyer buyer = buyerMapper.selectById(orderStore.getBuyerId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderStore", orderStore);
        jsonObject.put("logistics", logistics);
        jsonObject.put("goods", list);
        jsonObject.put("buyer",buyer);
        jsonObject.put("result", 1);
        return jsonObject;
    }



    /**
     * 发货，并且登记物流
     *
     * @param logisticsBean
     * @param orderStoreId 订单id
     * @param storeId 店铺id
     * @return true表示sql执行成功，false表示sql执行失败
     */
    @Transactional
    public boolean sendGoods(Logistics logisticsBean, Long orderStoreId, Integer storeId, Long dealUserId) {
        OrderStore orderStore = orderStoreDao.selectById(orderStoreId);
        int now = (int) (System.currentTimeMillis()/1000);
         Logistics logistics = logisticsDao.selectById(logisticsBean.getId());
         logistics.setLogisticsCode(logisticsBean.getLogisticsCode());
         logistics.setComment(logisticsBean.getComment());
         logistics.setSendTime(now);
        if (logisticsBean.getType() == 2) {
            //自提，核销
            logistics.setRecvTime(now);
        }else if (logisticsBean.getType() == 1){
            //邮寄需要设置发货信息，自提不需要设置发货信息，自提只需要更新物流状态和设置发货信息
            LogisticsCompany logisticsCompany = logisticsCompanyMapper.selectOneByStoreIdAndType(storeId,1);
            if (logisticsCompany==null){
                throw new LsException(CodeEnum.ERROR.getCode(),"请先设置店铺发货点信息");
            }
            logistics.setSendName(logisticsCompany.getContactsName());
            logistics.setSendMobile(logisticsCompany.getContactsMobile());
            logistics.setSrcAddress(logisticsCompany.getAddress());
            logistics.setLogisticsName(logisticsCompany.getName());
        }
        orderStore.setStat(TradeEnum.TRADE_WAIT_RECV.getCode());
        logisticsDao.updateById(logistics);
        orderStore.setSendTime(now);
        orderStoreDao.updateById(orderStore);

        //更新单个订单的交易状态
        orderGoodsDao.updateStatByOrderStoreId(TradeEnum.TRADE_WAIT_RECV.getCode(),orderStoreId);
        //更新整笔交易状态
        List<OrderStore> list = orderStoreDao.selectByTradeId(orderStore.getTradeId());
        boolean tradeUpdate= list.stream().allMatch(orderStore1 -> orderStore1.getStat()>3);
        if (tradeUpdate) {
            tradeDao.updateTradeStat(logisticsBean.getId(), orderStore.getTradeId(), storeId, dealUserId, 3);
        }
        dealQueueService.addRecv(orderStoreId);
        return true;
    }

    public String changeLogisticsPrice(Trade tradeBean) {
        if (tradeBean.getId() == null) {
            return "缺少id";
        }
        Trade tradeBean1 = tradeDao.selectById(tradeBean.getId());

        double changePrice = ((double) tradeBean1.getFreight()) - ((double) tradeBean.getFreight());
        tradeBean1.setFreight(tradeBean.getFreight());
        double paymoney = tradeBean1.getPayment() - changePrice;
        if (paymoney < 0) {
            return "商品支付价格不能为负数，请修改物流价格";
        }
        tradeBean1.setPayment((int) paymoney);
        Integer flag = tradeDao.updateFreightAndPaymentById(tradeBean1.getFreight(), tradeBean1.getPayment(), tradeBean1.getId());
        if (flag > 0) {
            return StringUtils.EMPTY;
        } else {
            return "数据库更新失败";
        }
    }

    @Transactional
    public boolean update(Trade tradeBean) {
        int sum = 0;
        for (OrderGoods orderGoodsBean : tradeBean.getOrderGoodsBeans()) {
            sum += orderGoodsBean.getTotalPrice();
            orderGoodsDao.updatePriceAndTotalPriceById(orderGoodsBean.getPrice(),
                    orderGoodsBean.getTotalPrice(),orderGoodsBean.getId()) ;
        }
        sum += tradeBean.getFreight();
        tradeBean.setPayment(sum);
        tradeDao.updateFreightAndPaymentById(tradeBean.getFreight(),tradeBean.getPayment(),
                tradeBean.getId());
        return true;
    }
}
